package com.xx.task;

import com.xx.common.constant.Constants;
import com.xx.utils.redis.RedisUtil;
import lombok.RequiredArgsConstructor;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.util.Set;

@Component
@RequiredArgsConstructor
public class RedisCleanupTask {

    private final RedisUtil redisUtil;


    // 每天凌晨执行，清理过期数据
    @Scheduled(cron = "0 0 1 * * ?")
    @Async
    public  void cleanExpiredData() {
        // 获取当前日期的前3天
        LocalDate localDate = LocalDate.now().minusDays(4);
        // 删除过期的数据
        String pattern = Constants.SHIP_TRACK_KEY + localDate + ":" +  "*";
        Set<String> keys = redisUtil.keys(pattern);
        if (CollectionUtils.isNotEmpty(keys)) {
            redisUtil.del(keys.toArray(new String[keys.size()]));
        }
   /*     for (String key : keys) {
            if (key.compareTo(pattern) <= 0) {
                redisUtil.del(key);
            }
        }*/
    }

}
